package com.liukaixin.product.ru.business.notice.systemnotice;

import android.os.Handler;
import android.support.annotation.NonNull;

import com.liukaixin.product.ru.data.CallBackListener;
import com.liukaixin.product.ru.data.model.Notice;
import com.liukaixin.product.ru.data.repositories.NoticeRepository;
import com.liukaixin.product.ru.enumerate.NoticeTypeEnum;
import com.liukaixin.product.ru.util.CheckUtil;

import java.util.List;

/**
 * Created by Jacob on 2016/9/20.
 */
public class SystemNoticesPresenter implements SystemNoticesContract.Presenter {

    @NonNull
    private final NoticeRepository noticeRepository;

    private final SystemNoticesContract.View systemView;

    private Handler handler = new Handler();

    public SystemNoticesPresenter(NoticeRepository noticeRepository,
                                  SystemNoticesContract.View systemView) {
        this.noticeRepository = noticeRepository;
        this.systemView = systemView;

        this.systemView.setPresenter(this);
    }

    @Override
    public void refresh(Integer categoryId) {

        systemView.initPage();
        // 获取第一页的十条数据
        getSystemNotice(1, 10);

    }

    @Override
    public void loadMore(Integer page, Integer categoryId) {
        // 获取第一页的十条数据
        getSystemNotice(page, 10);

    }


    private void getSystemNotice(Integer page, Integer rows) {
        if (CheckUtil.haveNetWork(systemView.getContext())) {
            noticeRepository.getNoticeById(page, rows,
                    NoticeTypeEnum.SYSTEM_NOTICE.getTypeCode(),
                    new CallBackListener<List<Notice>>() {
                        @Override
                        public void onCompleted() {
                            //do nothing
                        }

                        @Override
                        public void onError(String msg) {
                            systemView.showError(msg);
                        }

                        @Override
                        public void onNext(List<Notice> notices) {
                            handler.postDelayed(() -> {
                                if (page == 1 && notices.isEmpty()) {
                                    systemView.showNoData();
                                    return;
                                }
                                if (page == 1) {
                                    systemView.clearAdapter();
                                }
                                if (notices.size() % 10 > 0
                                        || (page != 1 && notices.isEmpty())) {
                                    systemView.setNoMoreData();
                                }
                                systemView.showData(notices);
                            }, 1000);
                        }

                    });
        }
    }

}
